package com.io.smartappframe.mvc.activity

import android.os.Bundle
import android.view.View
import android.widget.CompoundButton
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.io.base.mvc.BaseActivityMVC
import com.io.commonlib.helper.DateHelper
import com.io.commonlib.helper.LogHelper
import com.io.commonlib.helper.ToastHelper
import com.io.smartappframe.R
import com.io.smartappframe.databinding.ActivityAMapLocationBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class AMapLocationActivity : BaseActivityMVC<ActivityAMapLocationBinding>(), View.OnClickListener,
    AMapLocationListener, CompoundButton.OnCheckedChangeListener {
    private lateinit var mLocationClient: AMapLocationClient
    private lateinit var mLocationOption: AMapLocationClientOption

    override fun initView(savedInstanceState: Bundle?): ActivityAMapLocationBinding {
        return ActivityAMapLocationBinding.inflate(layoutInflater)
    }

    override fun initData(savedInstanceState: Bundle?) {
        mViewBinding.header.tvTitle.setText("高德地图定位测试")
        mViewBinding.header.ivToolbarBack.setOnClickListener(this)
        mViewBinding.btnLocationModeHightAccuracy.setOnClickListener(this)
        mViewBinding.btnLocationModeBatterySaving.setOnClickListener(this)
        mViewBinding.btnLocationModeDeviceSensors.setOnClickListener(this)
        mViewBinding.btnLocationContinuous.setOnClickListener(this)
        mViewBinding.btnLocationOnce.setOnClickListener(this)
        mViewBinding.btnStart.setOnClickListener(this)
        mViewBinding.btnStop.setOnClickListener(this)
        mViewBinding.checkboxAddressDesc.setOnCheckedChangeListener(this)
        mViewBinding.checkboxCache.setOnCheckedChangeListener(this)
        //初始化定位
        mLocationClient = AMapLocationClient(applicationContext)
        //设置定位回调监听
        mLocationClient.setLocationListener(this)
        mLocationOption = AMapLocationClientOption()

    }

    override fun onClick(v: View?) {
        v?.let {
            if (it.id == R.id.iv_toolbar_back) {
                finish()
            } else if (it.id == R.id.btn_location_mode_Hight_Accuracy) {
                mLocationOption.locationMode =
                    AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
            } else if (it.id == R.id.btn_location_mode_Battery_Saving) {
                mLocationOption.locationMode =
                    AMapLocationClientOption.AMapLocationMode.Battery_Saving
            } else if (it.id == R.id.btn_location_mode_Device_Sensors) {
                mLocationOption.locationMode =
                    AMapLocationClientOption.AMapLocationMode.Device_Sensors
            } else if (it.id == R.id.btn_location_Continuous) {
                mLocationOption.isOnceLocation = false
            } else if (it.id == R.id.btn_location_once) {
                mLocationOption.isOnceLocation = true
                mLocationOption.isOnceLocationLatest = true
            } else if (it.id == R.id.btn_start) {
                LogHelper.d(TAG, "mLocationClient--------------${mLocationClient.isStarted}")
                mLocationClient.startLocation()
            } else if (it.id == R.id.btn_stop) {
                LogHelper.d(TAG, "mLocationClient--------------${mLocationClient.isStarted}")
                mLocationClient.stopLocation()
            }
        }
    }

    override fun onLocationChanged(p0: AMapLocation?) {
        p0?.let {
            LogHelper.d(TAG, "onLocationChanged---定位数据不为空")
            var result = ""
            val timeStr = DateHelper.currentDateAndTimeStr
            result += "定位时间：${timeStr};\n"
            if (p0.errorCode == 0) {
                result += "LocationType：${converLocationTypeToString(p0.locationType)};\n"
                result += "Address：${p0.address};\n"
                result += "AoiName: ${p0.aoiName};\n"
                result += "PoiName: ${p0.poiName};\n"
                result += "Floor: ${p0.floor};\n"
            } else {
                result += "location Error, ErrCode: ${p0.errorCode}, errInfo：${p0.errorInfo}"
            }
            scope.launch(Dispatchers.Main) { mViewBinding.tvResultContent.setText(result) }
        } ?: let {
            LogHelper.d(TAG, "onLocationChanged---定位数据为空")
        }
    }

    override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
        buttonView?.let {
            if (buttonView.id == R.id.checkbox_address_desc) {
                if (isChecked) {
                    mLocationOption.isNeedAddress = true
                } else {
                    mLocationOption.isNeedAddress = false
                }
            } else if (buttonView.id == R.id.checkbox_cache) {
                if (isChecked) {
                    mLocationOption.isLocationCacheEnable = true
                } else {
                    mLocationOption.isLocationCacheEnable = false
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mLocationClient.stopLocation()
        mLocationClient.onDestroy()
        ToastHelper.cancelToast()
    }

    /**
     * 将当前定位结果来源从数字转成字符串
     */
    private fun converLocationTypeToString(type: Int): String {
        var result = ""
        when (type) {
            0 -> result = "定位失败"
            1 -> result = "GPS定位结果"
            2 -> result = "前次定位结果"
            4 -> result = "缓存定位结果"
            5 -> result = "Wifi定位结果"
            6 -> result = "基站定位结果"
            8 -> result = "离线定位结果"
            9 -> result = "最后位置缓存"
        }
        return result
    }
}